package com.tanger.pay.wechat;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Description 请求工具类
 * @Author Hchenbin
 * @Date 2024-01-04 17:22
 * @Version 1.0
 */
public class HttpUtil {

    private static final String METHOD_GET = "GET";
    private static final String METHOD_POST = "POST";
    private static final String REQUEST_TYPE_DEF = "application/x-www-form-urlencoded;charset=UTF-8";
    private static final String REQUEST_TYPE_JSON = "application/json;charset=UTF-8";
    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    public static String sendPost(String urlStr, String params) {
        String result = sendRequest(urlStr, params, METHOD_POST, REQUEST_TYPE_DEF);
        if (StringUtils.isNotBlank(result)) {
            return result;
        }
        return null;
    }

    public static String sendGet(String urlStr, String params) {
        if (StringUtils.isNotEmpty(params)) {
            if (urlStr.indexOf("?") > 0) {
                urlStr += "&" + params;
            } else {
                urlStr += "?" + params;
            }
        }
        String result = sendRequest(urlStr, null, METHOD_GET, REQUEST_TYPE_DEF);
        if (StringUtils.isNotBlank(result)) {
            return result;
        }
        return null;
    }

//    public static JSONObject sendJSONPost(String urlStr, JSONObject jsonParams) {
//        String params = "";
//        if (jsonParams != null) {
//            params = jsonParams.toJSONString();
//        }
//        String result = sendRequest(urlStr, params, METHOD_POST, REQUEST_TYPE_JSON);
//        if (StringUtils.isNotBlank(result)) {
//            JSONObject returnObj = JSONObject.parseObject(result);
//            return returnObj;
//        }
//        return null;
//    }

    private static String sendRequest(String urlStr, String jsonParams, String method, String type) {
        logger.info("正在发送HTTP请求：" + urlStr + "\n参数：" + jsonParams);
        PrintWriter out = null;
        BufferedReader in = null;
        DataOutputStream dos = null;
        StringBuilder result = new StringBuilder();
        try {
            URL url = new URL(urlStr);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            //设置参数
            //需要输出
            httpConn.setDoOutput(true);
            //需要输入
            httpConn.setDoInput(true);
            //设置POST方式连接
            httpConn.setRequestMethod(method);
            //设置请求属性
            httpConn.setRequestProperty("Content-Type", type);

            //建立输入流，向指向的URL传入参数
            if (StringUtils.isNotEmpty(jsonParams)) {
                if (REQUEST_TYPE_JSON.equals(type)) {
                    dos = new DataOutputStream(httpConn.getOutputStream());
                    dos.write(jsonParams.getBytes("utf-8"));
                } else {
                    // 获取URLConnection对象对应的输出流
                    httpConn.getOutputStream().write(jsonParams.getBytes("utf-8"));
                    //out = new PrintWriter(httpConn.getOutputStream());
                    // 发送请求参数
                    //out.print(jsonParams);
                }
            }
            //获得响应状态
            int resultCode = httpConn.getResponseCode();
            if (HttpURLConnection.HTTP_OK == resultCode) {
                String readLine;
                in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
                while ((readLine = in.readLine()) != null) {
                    result.append(readLine).append("\n");
                }
            } else if (HttpURLConnection.HTTP_BAD_REQUEST == resultCode) {
//                throw new BusinessException("请求参数异常");
                logger.error("请求参数异常");
            }else if (HttpURLConnection.HTTP_NOT_FOUND== resultCode) {
//                throw new BusinessException("请求的地址不存在");
                logger.error("请求的地址不存在");
            }
        } catch (ConnectException e) {
//            throw new BusinessException("网络连接异常或服务未启动");
        } catch (Exception e) {
            logger.error("发送HTTP请求异常:" + urlStr, e);
        } finally {
            try {
                if (dos != null) {
                    dos.flush();
                    dos.close();
                }
                if (out != null) {
                    out.flush();
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        return result.toString();
    }
}
